import React, { useState, useEffect } from 'react'
import {
  Card,
  List,
  Space,
  Button,
  Typography,
  Tag,
  Tooltip,
  Input,
  Select,
  Pagination,
  Empty,
  Modal,
  Popconfirm,
} from 'antd'
import {
  HistoryOutlined,
  PlayCircleOutlined,
  DeleteOutlined,
  EyeOutlined,
  CopyOutlined,
  SearchOutlined,
  FilterOutlined,
  ClockCircleOutlined,
} from '@ant-design/icons'
import { formatDateTime, formatDuration, copyToClipboard } from '@/utils'

const { Text, Paragraph } = Typography
const { Search } = Input
const { Option } = Select

export interface ExecutionHistoryItem {
  id: string
  sql: string
  connection_name: string
  connection_id: string
  status: 'completed' | 'failed' | 'cancelled'
  start_time: string
  end_time?: string
  duration: number
  rows_affected?: number
  rows_returned?: number
  error_message?: string
  created_by: string
}

interface ExecutionHistoryProps {
  history: ExecutionHistoryItem[]
  loading?: boolean
  onExecute?: (sql: string, connectionId: string) => void
  onDelete?: (id: string) => void
  onClear?: () => void
  onLoadMore?: () => void
  hasMore?: boolean
  maxHeight?: number
}

const ExecutionHistory: React.FC<ExecutionHistoryProps> = ({
  history,
  loading = false,
  onExecute,
  onDelete,
  onClear,
  onLoadMore,
  hasMore = false,
  maxHeight = 400,
}) => {
  const [searchText, setSearchText] = useState('')
  const [statusFilter, setStatusFilter] = useState<string>('')
  const [connectionFilter, setConnectionFilter] = useState<string>('')
  const [detailModalVisible, setDetailModalVisible] = useState(false)
  const [selectedItem, setSelectedItem] = useState<ExecutionHistoryItem | null>(null)

  // 过滤历史记录
  const filteredHistory = history.filter(item => {
    const matchesSearch = !searchText || 
      item.sql.toLowerCase().includes(searchText.toLowerCase()) ||
      item.connection_name.toLowerCase().includes(searchText.toLowerCase())
    
    const matchesStatus = !statusFilter || item.status === statusFilter
    const matchesConnection = !connectionFilter || item.connection_id === connectionFilter
    
    return matchesSearch && matchesStatus && matchesConnection
  })

  // 获取状态标签
  const getStatusTag = (status: string) => {
    switch (status) {
      case 'completed':
        return <Tag color="success">成功</Tag>
      case 'failed':
        return <Tag color="error">失败</Tag>
      case 'cancelled':
        return <Tag color="default">已取消</Tag>
      default:
        return <Tag>{status}</Tag>
    }
  }

  // 获取唯一连接列表
  const uniqueConnections = Array.from(
    new Set(history.map(item => item.connection_id))
  ).map(id => {
    const item = history.find(h => h.connection_id === id)
    return { id, name: item?.connection_name || id }
  })

  // 处理重新执行
  const handleReExecute = (item: ExecutionHistoryItem) => {
    onExecute?.(item.sql, item.connection_id)
  }

  // 处理复制SQL
  const handleCopySQL = async (sql: string) => {
    const success = await copyToClipboard(sql)
    if (success) {
      // message.success('SQL已复制到剪贴板')
    }
  }

  // 处理查看详情
  const handleViewDetail = (item: ExecutionHistoryItem) => {
    setSelectedItem(item)
    setDetailModalVisible(true)
  }

  // 处理删除
  const handleDelete = (id: string) => {
    onDelete?.(id)
  }

  // 渲染历史项
  const renderHistoryItem = (item: ExecutionHistoryItem) => (
    <List.Item
      key={item.id}
      actions={[
        <Tooltip title="重新执行">
          <Button
            type="text"
            size="small"
            icon={<PlayCircleOutlined />}
            onClick={() => handleReExecute(item)}
          />
        </Tooltip>,
        <Tooltip title="复制SQL">
          <Button
            type="text"
            size="small"
            icon={<CopyOutlined />}
            onClick={() => handleCopySQL(item.sql)}
          />
        </Tooltip>,
        <Tooltip title="查看详情">
          <Button
            type="text"
            size="small"
            icon={<EyeOutlined />}
            onClick={() => handleViewDetail(item)}
          />
        </Tooltip>,
        <Popconfirm
          title="确定删除这条执行记录吗？"
          onConfirm={() => handleDelete(item.id)}
          okText="删除"
          cancelText="取消"
        >
          <Tooltip title="删除">
            <Button
              type="text"
              size="small"
              danger
              icon={<DeleteOutlined />}
            />
          </Tooltip>
        </Popconfirm>,
      ]}
    >
      <List.Item.Meta
        title={
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            {getStatusTag(item.status)}
            <Text style={{ fontSize: 12, color: '#666' }}>
              {formatDateTime(item.start_time)}
            </Text>
            <Text style={{ fontSize: 12, color: '#666' }}>
              {item.connection_name}
            </Text>
          </div>
        }
        description={
          <div>
            <Paragraph
              ellipsis={{ rows: 2, expandable: true, symbol: '展开' }}
              style={{ 
                margin: 0, 
                fontSize: 12,
                fontFamily: 'Monaco, Consolas, monospace',
                background: '#f5f5f5',
                padding: '4px 8px',
                borderRadius: 4,
              }}
            >
              {item.sql}
            </Paragraph>
            
            <div style={{ marginTop: 8, display: 'flex', gap: 12 }}>
              <Space size={4}>
                <ClockCircleOutlined style={{ fontSize: 11, color: '#666' }} />
                <Text style={{ fontSize: 11, color: '#666' }}>
                  {formatDuration(item.duration)}
                </Text>
              </Space>
              
              {item.rows_returned !== undefined && (
                <Text style={{ fontSize: 11, color: '#666' }}>
                  返回 {item.rows_returned} 行
                </Text>
              )}
              
              {item.rows_affected !== undefined && (
                <Text style={{ fontSize: 11, color: '#666' }}>
                  影响 {item.rows_affected} 行
                </Text>
              )}
              
              <Text style={{ fontSize: 11, color: '#666' }}>
                {item.created_by}
              </Text>
            </div>
            
            {item.error_message && (
              <Text type="danger" style={{ fontSize: 11, display: 'block', marginTop: 4 }}>
                {item.error_message}
              </Text>
            )}
          </div>
        }
      />
    </List.Item>
  )

  return (
    <Card 
      title={
        <Space>
          <HistoryOutlined />
          <span>执行历史</span>
          <Text type="secondary">({filteredHistory.length})</Text>
        </Space>
      }
      size="small"
      extra={
        onClear && (
          <Popconfirm
            title="确定清空所有执行历史吗？"
            onConfirm={onClear}
            okText="清空"
            cancelText="取消"
          >
            <Button type="text" size="small" danger>
              清空
            </Button>
          </Popconfirm>
        )
      }
    >
      {/* 搜索和过滤 */}
      <div style={{ marginBottom: 12 }}>
        <Space>
          <Search
            placeholder="搜索SQL或连接名..."
            style={{ width: 200 }}
            size="small"
            value={searchText}
            onChange={(e) => setSearchText(e.target.value)}
          />
          
          <Select
            placeholder="状态"
            style={{ width: 100 }}
            size="small"
            value={statusFilter}
            onChange={setStatusFilter}
            allowClear
          >
            <Option value="completed">成功</Option>
            <Option value="failed">失败</Option>
            <Option value="cancelled">已取消</Option>
          </Select>
          
          <Select
            placeholder="连接"
            style={{ width: 120 }}
            size="small"
            value={connectionFilter}
            onChange={setConnectionFilter}
            allowClear
          >
            {uniqueConnections.map(conn => (
              <Option key={conn.id} value={conn.id}>
                {conn.name}
              </Option>
            ))}
          </Select>
        </Space>
      </div>

      {/* 历史列表 */}
      <div style={{ maxHeight, overflow: 'auto' }}>
        {filteredHistory.length === 0 ? (
          <Empty
            image={Empty.PRESENTED_IMAGE_SIMPLE}
            description="暂无执行历史"
            style={{ padding: '20px 0' }}
          />
        ) : (
          <List
            dataSource={filteredHistory}
            renderItem={renderHistoryItem}
            loading={loading}
            size="small"
          />
        )}
      </div>

      {/* 加载更多 */}
      {hasMore && (
        <div style={{ textAlign: 'center', marginTop: 12 }}>
          <Button size="small" onClick={onLoadMore} loading={loading}>
            加载更多
          </Button>
        </div>
      )}

      {/* 详情模态框 */}
      <Modal
        title="执行详情"
        open={detailModalVisible}
        onCancel={() => setDetailModalVisible(false)}
        footer={[
          <Button key="close" onClick={() => setDetailModalVisible(false)}>
            关闭
          </Button>,
          selectedItem && (
            <Button 
              key="rerun" 
              type="primary"
              icon={<PlayCircleOutlined />}
              onClick={() => {
                handleReExecute(selectedItem)
                setDetailModalVisible(false)
              }}
            >
              重新执行
            </Button>
          ),
        ]}
        width={800}
      >
        {selectedItem && (
          <div>
            <Space direction="vertical" style={{ width: '100%' }} size="middle">
              <div>
                <Text strong>状态：</Text>
                {getStatusTag(selectedItem.status)}
              </div>
              
              <div>
                <Text strong>连接：</Text>
                <Text>{selectedItem.connection_name}</Text>
              </div>
              
              <div>
                <Text strong>执行时间：</Text>
                <Text>{formatDateTime(selectedItem.start_time)}</Text>
                {selectedItem.end_time && (
                  <Text type="secondary"> - {formatDateTime(selectedItem.end_time)}</Text>
                )}
              </div>
              
              <div>
                <Text strong>耗时：</Text>
                <Text>{formatDuration(selectedItem.duration)}</Text>
              </div>
              
              {selectedItem.rows_returned !== undefined && (
                <div>
                  <Text strong>返回行数：</Text>
                  <Text>{selectedItem.rows_returned}</Text>
                </div>
              )}
              
              {selectedItem.rows_affected !== undefined && (
                <div>
                  <Text strong>影响行数：</Text>
                  <Text>{selectedItem.rows_affected}</Text>
                </div>
              )}
              
              <div>
                <Text strong>执行者：</Text>
                <Text>{selectedItem.created_by}</Text>
              </div>
              
              <div>
                <Text strong>SQL语句：</Text>
                <div style={{ 
                  marginTop: 8,
                  padding: 12,
                  background: '#f5f5f5',
                  borderRadius: 6,
                  fontFamily: 'Monaco, Consolas, monospace',
                  fontSize: 12,
                  whiteSpace: 'pre-wrap',
                  maxHeight: 200,
                  overflow: 'auto',
                }}>
                  {selectedItem.sql}
                </div>
              </div>
              
              {selectedItem.error_message && (
                <div>
                  <Text strong type="danger">错误信息：</Text>
                  <div style={{ 
                    marginTop: 8,
                    padding: 12,
                    background: '#fff2f0',
                    border: '1px solid #ffccc7',
                    borderRadius: 6,
                    fontSize: 12,
                    color: '#ff4d4f',
                  }}>
                    {selectedItem.error_message}
                  </div>
                </div>
              )}
            </Space>
          </div>
        )}
      </Modal>
    </Card>
  )
}

export default ExecutionHistory